package cn.coldleaf.wiki.interceptors;

import cn.coldleaf.wiki.pojo.vo.ResponseVo;
import cn.coldleaf.wiki.utils.ErrorCode;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @datetime 2023/10/15 下午4:19
 * @user cold
 **/
@ControllerAdvice("cn.coldleaf.wiki.controllers")
public class WikiResponse implements ResponseBodyAdvice<ResponseVo<?>> {
    /**
     * Whether this component supports the given controller method return type
     * and the selected {@code HttpMessageConverter} type.
     *
     * @param returnType    the return type
     * @param converterType the selected converter type
     * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
     * {@code false} otherwise
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * Invoked after an {@code HttpMessageConverter} is selected and just before
     * its write method is invoked.
     *
     * @param body                  the body to be written
     * @param returnType            the return type of the controller method
     * @param selectedContentType   the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request               the current request
     * @param response              the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    @Override
    public ResponseVo<?> beforeBodyWrite(ResponseVo<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null){
            if (body.getCode() == ErrorCode.EXCEPTION.getCode()){
                response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            }else if (body.getCode() == ErrorCode.PARAM_ERROR.getCode()){
                response.setStatusCode(HttpStatus.BAD_REQUEST);
            }else if (body.getCode() == ErrorCode.AUTH_ERROR.getCode()){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
            }else {
                response.setStatusCode(HttpStatus.OK);
            }
        }else {
            body = ResponseVo.exception();
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return body;
    }
}
